"""
Boss Agent 快速测试脚本

快速验证Agent是否正常工作
"""
import os
import sys

# 添加项目路径
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

# 设置Django环境
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'boss.settings')
import django
django.setup()


def check_environment():
    """检查环境配置"""
    print("🔍 检查环境配置...")
    
    # 检查API Key
    api_key = os.getenv("DASHSCOPE_API_KEY")
    if not api_key:
        print("❌ 错误: DASHSCOPE_API_KEY 未设置")
        print("请执行: export DASHSCOPE_API_KEY=your_api_key")
        return False
    else:
        print(f"✅ API Key已设置: {api_key[:10]}...")
    
    # 检查Redis
    try:
        import redis
        r = redis.Redis(host='localhost', port=6380, db=11)
        r.ping()
        print("✅ Redis连接正常")
    except Exception as e:
        print(f"⚠️  Redis连接失败: {str(e)}")
        print("记忆功能可能不可用（但Agent仍可运行）")
    
    # 检查Django
    try:
        from home.models import Jobposting
        count = Jobposting.objects.count()
        print(f"✅ Django ORM正常，职位数量: {count}")
    except Exception as e:
        print(f"⚠️  Django ORM异常: {str(e)}")
    
    return True


def test_agent_initialization():
    """测试Agent初始化"""
    print("\n🤖 测试Agent初始化...")
    
    try:
        from agent.boss_agent import BossAgent
        agent = BossAgent(verbose=False)
        print(f"✅ Agent初始化成功")
        print(f"   - 工具数量: {len(agent.tools)}")
        print(f"   - LLM模型: qwen-plus")
        return agent
    except Exception as e:
        print(f"❌ Agent初始化失败: {str(e)}")
        import traceback
        traceback.print_exc()
        return None


def test_simple_chat(agent):
    """测试简单对话"""
    print("\n💬 测试简单对话...")
    
    try:
        result = agent.chat(
            user_input="你好，请介绍一下你自己",
            user_id=9999,
            session_id="quick_test_001"
        )
        
        if result['success']:
            print("✅ 对话成功")
            print(f"\n📝 Agent回复:")
            print("-" * 60)
            print(result['output'])
            print("-" * 60)
            print(f"\n📊 统计:")
            print(f"   - 工具调用: {result.get('tool_calls', 0)}次")
        else:
            print(f"❌ 对话失败: {result.get('error')}")
            
    except Exception as e:
        print(f"❌ 对话异常: {str(e)}")
        import traceback
        traceback.print_exc()


def test_tool_call(agent):
    """测试工具调用"""
    print("\n🛠️  测试工具调用...")
    
    try:
        result = agent.chat(
            user_input="帮我查询Python工程师职位",
            user_id=9999,
            session_id="quick_test_002"
        )
        
        if result['success']:
            print("✅ 工具调用成功")
            print(f"   - 调用了{result.get('tool_calls', 0)}个工具")
            print(f"\n📝 Agent回复:")
            print("-" * 60)
            print(result['output'][:300])
            print("-" * 60)
        else:
            print(f"❌ 工具调用失败: {result.get('error')}")
            
    except Exception as e:
        print(f"❌ 工具调用异常: {str(e)}")


def main():
    """主函数"""
    print("\n" + "=" * 60)
    print("🚀 Boss Agent 快速测试")
    print("=" * 60)
    
    # 1. 检查环境
    if not check_environment():
        print("\n❌ 环境检查失败，请先配置环境")
        return
    
    # 2. 初始化Agent
    agent = test_agent_initialization()
    if not agent:
        print("\n❌ Agent初始化失败，测试终止")
        return
    
    # 3. 测试简单对话
    test_simple_chat(agent)
    
    # 4. 测试工具调用
    test_tool_call(agent)
    
    # 总结
    print("\n" + "=" * 60)
    print("✅ 快速测试完成！")
    print("=" * 60)
    print("\n📖 后续操作:")
    print("   1. 运行完整测试: python agent/tests/test_agent.py")
    print("   2. 运行使用示例: python agent/example_usage.py")
    print("   3. 启动Django服务: python manage.py runserver")
    print("   4. 调用API: curl -X POST http://localhost:8000/agent/chat/")
    print("=" * 60)


if __name__ == '__main__':
    main()


